package com.example.netty.util;

import com.example.netty.bean.DeviceMsg;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.nio.cs.ext.MacCentralEurope;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Author : lichong
 * @description :
 * @Date Create in 22:26 2020/1/21
 * @Modified By :
 **/
public class SessionUtils {
    private static final Logger logger = LoggerFactory.getLogger(SessionUtils.class);
    private static ConcurrentMap<String, ChannelHandlerContext> sessions = new ConcurrentHashMap();

    private static String snno = "A00000000002";
    /**
     * 保存回话信息到缓存中
     * @param ctx
     * @param msg
     */
    public static void putSession(ChannelHandlerContext ctx, DeviceMsg msg) {
        sessions.putIfAbsent(msg.getSnNo(), ctx);
    }

    /**
     * 给其他发送信息
     * @param msg
     */
    public static void writeMsg(DeviceMsg msg) {
        ChannelHandlerContext ctx = sessions.get(snno);
        if (ctx != null) {
            String str = getMsg(msg);
            logger.info("输出信息....{}", str);
            ctx.writeAndFlush(str);
        }
    }

    /**
     * 给其他发送信息
     */
    public static void remove() {
        sessions.clear();
    }

    /**
     * 获取相应信息
     * @param msg
     * @return
     */
    public static String getMsg(DeviceMsg msg) {
        String timeStr = DateUtils.getStringDate("mm:ss", msg.getTime());
        return timeStr + "," + msg.getData();
    }
}
